/*******************************************************************************
 * Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * Copyright (c) 2011- kotemaru@kotemaru.org
 ******************************************************************************/
package org.kotemaru.gae.dstool.client;

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.*;
import org.kotemaru.util.json.*;
import org.mortbay.log.Log;

/**
 * BackupServlet用のクライアント。
 * <li>TODO:認証処理
 */
public class DsToolClient {
	public static final String DSTOOL_PROPS = "dstool.props";

	/**
	 * コマンド入口
	 */
	public static void main(String[] args)
		throws Exception 
	{
		int limit = 100;
		String file = null;
		List<String> argList = new ArrayList<String>(args.length);
		for (int i=0; i<args.length; i++) {
			if (args[i].startsWith("-limit=")) {
				limit = Integer.parseInt(args[i].substring(7));
			} else if (args[i].startsWith("-file=")) {
				file = args[i].substring(6);
			} else {
				argList.add(args[i]);
			}
		}

		if (argList.size() < 3) {
			usage();
			return;
		}
		String command = argList.get(0);
		String url     = argList.get(1);
		String kind    = argList.get(2);
		
		Properties props = ClientUtil.loadProps("oauth.props", null, true);
		GaeOAuthClient client = new GaeOAuthClient(props);

		if ("download".equals(command)) {
			Writer writer = ClientUtil.takeWriter(file);
			EntityDownloader dler = new EntityDownloader(client, writer, url, kind);
			dler.setLimit(limit);
			dler.download();
		} else if ("upload".equals(command)) {
			Reader reader = ClientUtil.takeReader(file);
			EntityUploader uler = new EntityUploader(client, url, kind);
			uler.setLimit(limit);
			uler.upload(reader);
		} else {
			usage();
			return;
		}
	}

	private static void usage() {
		String usage = 
			 "Usage: java DsTool <command> [-limit=<n>] [-file=<file>] <url> <kind>\n"
			+"   <command>: download or upload.\n"
			+"       download  : Download JSON format entities from <url>.\n"
			+"       upload    : Upload JSON format entities to <url>.\n"
			+"   <url>: DsToolServlet URL. Ex. https://dstool.app-id.appspot.com/dstool\n"
			+"   <kind>: DataStore kind. Ex. Employee\n"
			+"\n"
			+"   -limit=<n>: The number of the limits of the entity to handle at one request. default=100.\n"
			+"   -file=<file>: Output or input JSON file. default=stdin/stdout.\n"
		;
		System.err.println(usage);
		//System.exit(0);
	}
	

}
